package com.gsit.expenditure.utils;

import java.io.IOException;

import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

import com.gsit.expenditure.client.domina.FXMLBase;

public class ViewHandler {

	private static final String PAGE_PATH = "views";
	private static final String PATH_SEPARATOR = "/";
	private static final String DOT = ".";
	private static final String FILE_EXT = "fxml";

	private static Stage mainStage;

	public static void setMainStage(Stage stage) {
		ViewHandler.mainStage = stage;
	}

	public static Stage getMainStage() {
		return ViewHandler.mainStage;
	}

	public static Node loadPage(Page page) {
		Node root = null;
		try {
			
			root = FXMLLoader.load(ViewHandler.class.getResource(createPageName(page)));
			
		} catch (IOException e) {
			e.printStackTrace();
		}

		return root;
	}

	public static FXMLLoader createAndloadFXMLLoader(Page page) {
		FXMLLoader fxmlLoader = null;
		fxmlLoader = new FXMLLoader(
				ViewHandler.class.getResource(createPageName(page)));

		return fxmlLoader;
	}

	public static FXMLBase createFXMLBase(Page page) {
		FXMLBase fXMLBase = new FXMLBase(new FXMLLoader(ViewHandler.class.getResource(createPageName(page))));
		return fXMLBase;
	}

	public static FXMLBase createDialog(FXMLBase fxmlBase, String title) {
		Scene scene = new Scene(fxmlBase.getRoot());
		Stage dialogStage = new Stage();
		dialogStage.setTitle(title);
		dialogStage.setResizable(false);
		dialogStage.initModality(Modality.WINDOW_MODAL);
		dialogStage.initOwner(ViewHandler.getMainStage());
		dialogStage.setScene(scene);
		dialogStage.initStyle(StageStyle.UTILITY);

		fxmlBase.setDialogStage(dialogStage);

		return fxmlBase;

	}

	

	private static String createPageName(Page page) {
		StringBuffer pagePath = new StringBuffer();
		pagePath.append(PATH_SEPARATOR);
		pagePath.append(PAGE_PATH);
		pagePath.append(PATH_SEPARATOR);
		pagePath.append(page.getFolder());
		pagePath.append(PATH_SEPARATOR);
		pagePath.append(page.getPageName());
		pagePath.append(DOT);
		pagePath.append(FILE_EXT);
		return pagePath.toString();
	}

}
